<script setup lang="ts">
import VChart from 'vue-echarts'
import type { TooltipComponentFormatterCallback } from 'echarts'
import { useChartAutoResize } from '@/mixins/MixinChartAutoResize'
import { useChartTooltipTheme } from '@/mixins/MixinChartTooltipTheme'
import type { VChartInstance } from '@/types'
import { defaultNumber } from '@/utils'

const props = defineProps<{
  data: any[]
  name: string
}>()
const pieTooltipFormatter: TooltipComponentFormatterCallback<any>
= ({ color, percent, name, value, data, ...rest }) => {
  return `
    <div style="margin: 0;line-height:1;">
      <div style="font-size:14px;color:var(--el-text-color-regular);font-weight:400;line-height:1;">${rest.seriesName || name}</div>
      <div style="margin: 10px 0 0;line-height:1;">
        <div style="margin: 0;line-height:1.5;">
          <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>
          <span style="font-size:14px;color:var(--el-text-color-regular);font-weight:400;margin-left:2px">${name}：</span>
          <span style="font-size:14px;color:var(--el-text-color-regular);font-weight:900">${defaultNumber(data[1])}（${percent}%）</span>
       </div>
      </div>
    </div>
  `
}
const tooltipTheme = useChartTooltipTheme()
const chartOption = computed(() => {
  return {
    darkMode: 'auto',
    title: {
      text: props.name,
      top: 10,
      left: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: pieTooltipFormatter,
      ...tooltipTheme,
    },
    legend: {
      left: 'center',
      bottom: 20,
    },
    series: [
      {
        type: 'pie',
        radius: '60%',
        center: ['50%', '45%'],
        name: props.name,
        seriesLayoutBy: 'row',
        label: {
          show: false,
        },
      },
    ],
    dataset: {
      source: props.data || [],
    },
  }
})

const chartRef = ref<VChartInstance>()
useChartAutoResize(chartRef)

const { theme } = storeToRefs(useDesignStore())
watchEffect(() => {
  if (chartRef.value) {
    chartRef.value.setOption({
      theme: theme.value,
    })
  }
})
</script>

<template>
  <VChart
    ref="chartRef" :option="chartOption"
    :theme="theme"
  />
</template>
